package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: yuking
 * @Date: 2025/9/16 - 09 - 16 - 21:38
 * @Description: com.sky.service.admin
 * @version: 1.0
 */

@Slf4j
@Service
public class DishServiceImpl implements DishService {
@Autowired
private DishMapper dishMapper;
@Autowired
private DishFlavorMapper dishFlavorMapper;
@Autowired
private SetmealDishMapper setmealDishMapper;

@Transactional
@Override
public void saveWithFlavor(DishDTO dishDTO) {
    Dish dish = new Dish();
    BeanUtils.copyProperties(dishDTO,dish);

    dishMapper.insert(dish);

    Long id = dish.getId();

    List<DishFlavor> flavor = dishDTO.getFlavors();

    if (flavor != null && flavor.size() > 0){
        flavor.forEach(dishFlavor -> {
            dishFlavor.setDishId(id);
        });
        dishFlavorMapper.insertBatch(flavor);
    }
}

@Override
public PageResult findByPage(DishPageQueryDTO dishPageQueryDTO) {
    PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
    Page<DishVO> page = dishMapper.findByPage(dishPageQueryDTO);
    return new PageResult(page.getTotal(), page.getResult());
}
@Transactional
@Override
public void deleteByIds(List<Long> ids) {
    Integer count1 = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
    if (count1>0){
        throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
    }
    Integer count2 = setmealDishMapper.selectCountByIds(ids);
    if (count2>0){
        throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
    }
    dishFlavorMapper.deleteByIds(ids);

    dishMapper.deleteByIds(ids);
}
}
